<template>
  <div class="h100 ecuVersionConfigInfo commonTableSty" ref="groupInfoTableList">
    <a-table
      ref="ecuVersionConfigTable"
      class="h100"
      :components="tableComponents"
      :columns="columns"
      :loading="loadingTbData"
      :dataSource="ecuVersionLists"
      :pagination="false"
      :scroll="{ x: 1190, y: 500 }"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: onGetCheckboxProps,
        fixed: true,
        columnWidth: 40,
      }"
      :rowKey="(record) => record.ecuId"
    >
      <!-- 自定义依赖分组列 -->
      <span slot="dependentGroupingColumn">
        {{ $t('dependentGrouping') }}
        <question-mark-tip
          :tip-title="$t('dependentGroupingColumnTip')"
          :popupContainer="getPopupContainerColumn"
        ></question-mark-tip>
      </span>
      <!-- 自定义是否回滚列 -->
      <span slot="isRollbackColumn">
        {{ $t('isRollback') }}
        <question-mark-tip
          :tip-title="$t('isRollbackColumnTip')"
          :popupContainer="getPopupContainerColumn"
        ></question-mark-tip>
      </span>
      <!-- 自定义升级顺序列 -->
      <span slot="updateOrderColumn">
        {{ $t('updateOrder') }}
        <question-mark-tip
          :tip-title="$t('updateOrderColumnTip')"
          :popupContainer="getPopupContainerColumn"
        ></question-mark-tip>
      </span>
      <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
        <table-ellipsis :text="text || '-'" :key="column.dataIndex"></table-ellipsis>
      </template>
      <template slot="versionDesc" slot-scope="text, record">
        <a @click="showVersionDesc(record)" v-if="record.versionlists && record.versionId">{{ $t('view') }}</a>
        <span v-else>-</span>
      </template>
      <template slot="ecuVersion" slot-scope="text,record">
        <VersionSelect v-model="record.versionId" :clear="true" :getPopupContainer="(n) => $refs.ecuVersionConfigTable.$el.querySelector('.ant-table-scroll')"
                       :onlyVersionType="versionType === 'TEST' ? '' : 'PROD'"
                       :lazy-load="true"
                       :default-data="record.versionId ? {'id':record.versionId,'name':record.versionName, 'versionType':record.versionType} : null"
                       :defaultVersionType="record.versionType"
                       :ecuModuleId="record.ecuModuleId"
                       @changeOption="(id, item) => handleSelectVersion(id, record,item,true)"
        />
<!--        <common-select-->
<!--          :key="record.ecuId"-->
<!--          :default-value="record.versionId"-->
<!--          :options="record.versionlists"-->
<!--          :allow-clear="false"-->
<!--          :show-search="true"-->
<!--          :getPopupContainer="getPopupContainerColumn"-->
<!--          @changeoption="handleSelectVersion($event, record)"-->
<!--        ></common-select>-->
      </template>
      <template slot="wholePackageCount" slot-scope="text, record">
        <span v-if="record.wholePackageCount">{{ $t('uploaded') }}</span>
        <span v-else>{{ $t('noUploaded') }}</span>
      </template>
      <template slot="dependentGrouping" slot-scope="text, record">
        <a-input-number :min="1" :max="999" :precision="0" v-model="record.groupNo" />
      </template>
      <template slot="updateOrder" slot-scope="text, record">
        <a-input-number :min="1" :max="999" :precision="0" v-model="record.groupUpgradeNo" />
      </template>
      <template slot="isRollback" slot-scope="text, record">
        <rollback-select
          :defaultValue="typeof record.groupRollback !== 'undefined' ? Number(record.groupRollback): undefined"
          @changeoption="handleSelectRollback($event, record)"
        ></rollback-select>
      </template>
    </a-table>
    <!-- 发布说明弹框组件 -->
    <view-release-note
      ref="releaseNoteRef"
      :width="600"
      :releaseNotes="releaseNotes"
      :is-edit="false"
    ></view-release-note>
  </div>
</template>
<script>
import { ecuVersionConfigColumns } from '../config/list'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import CommonSelect from '@/components/SelfComponents/CommonSelect.vue'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import PartSoftSelect from '@/views/components/PartSoftSelect'
import RollbackSelect from '@/views/components/RollbackSelect'
import ViewReleaseNote from '@/views/components/ViewReleaseNote'
import versionApi from '@/api/modules/software/partsVersion'
import { STable } from '@/components'
import tableDraggable from '@/utils/tableDraggable'
import VersionSelect from '@/views/components/VersionSelect'

export default {
  components: {
    tableEllipsis,
    CommonSelect,
    PartSoftSelect,
    RollbackSelect,
    STable,
    VersionSelect,
    QuestionMarkTip,
    ViewReleaseNote
  },
  props: {
    time: {
      type: Number,
      default: 110022
    },
    modelId: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    versionType: {
      type: String,
      default: ''
    },
    // 默认选中零件版本配置
    defaultVersions: {
      type: Object,
      default () {
        return null
      }
    }
  },
  computed: {
    commonColumns () {
      return this.columns.filter((item) => !item.special)
    }
  },
  data () {
    return {
      tbData: [],
      columns: [...ecuVersionConfigColumns].filter(item => item.dataIndex !== 'versionType'),
      // 零件软件下拉选项
      partsSoftwareOptions: [],
      // 禁用的零件软件选项列表
      disabledPartSoftOptions: [],
      // 版本下接选项数据
      versionOptions: {},
      ecuVersionLists: [{}],
      loadingTbData: false,
      // 已选中的表格行keys
      selectedRowKeys: [],
      releaseNotes: null,
      // 编辑时获取到新增时做的零件版本配置信息列表初始值，解决零件版本配置信息列表未做改动则传递空数组给后端
      defaultEcuConfigLists: [],
      // 没有全包和差分包不能勾选
      onGetCheckboxProps: (record) => {
        return {
          props: {
            disabled: !record.wholePackageCount && !record.patchPackageCount
          }
        }
      },
      ecuVersionsList: []
    }
  },
  watch: {
    time: {
      handler () {
      // 获取配置文件版本
        if(!this.id) {
          this.getCurEcuVersionConfigData()
          return
        }
        this.$api.getVehicleVersionDetailById(this.id, this.versionType).then((res) => {
          this.ecuVersionsList = res.data.ecuVersions
          this.getCurEcuVersionConfigData()
        })
      },
      immediate: true
    }
  },
  created () {
    this.tableComponents = tableDraggable(this.columns)
  },
  mounted () {},
  methods: {
    getPopupContainerColumn () {
      return document.body
    },
    // 获取当前选择的车型对应的零件版本列表
    getCurEcuVersionConfigData () {
      this.resetData()
      if (!this.modelId) {
        return
      }
      this.loadingTbData = true
      //加载车型ECU配置
      let modelEcuConfig = this.$api.getModelEcuConfig(this.modelId);
      versionApi.versionEcuSelect({ modelId: this.modelId }, this.versionType).then(res => modelEcuConfig.then((ecuConfigs) => {
        const data = res.data
        const defaultEcuLists = []
        this.ecuVersionLists = data.map(item => {
          let selectedVersion = this.defaultVersions ? this.defaultVersions[item.id] : null
          //新建时，没有初始内容，使用车型ECU配置中数据
          let ecuConfig = ecuConfigs.data.find(config => config.ecuModuleId === item.ecuModuleId);
          if (ecuConfig && !selectedVersion) {
            selectedVersion = {
              groupNo : ecuConfig.groupNo,
              groupUpgradeNo : ecuConfig.groupUpgradeNo,
              groupRollback: true,
              releaseNotes : null
            };
            if(ecuConfig.hasOwnProperty('groupRollback')) {
              selectedVersion.groupRollback = ecuConfig.groupRollback;
            }
          }
          return {
            partName: item.name,
            // 展示时用的ecuId
            showEcuId: item.ecuModuleId || '-',
            // 存储时用的ecuId
            ecuId: item.id,
            ecuModuleId: item.ecuModuleId,
            groupNo: selectedVersion ? selectedVersion.groupNo : null,
            groupRollback: selectedVersion ? selectedVersion.groupRollback : true,
            groupUpgradeNo: selectedVersion ? selectedVersion.groupUpgradeNo : null,
            versionId: undefined,
            softwareCode: item.softwareCode,
            configVersionName: selectedVersion.configVersionName,
            releaseNotes: selectedVersion ? selectedVersion.releaseNotes : null,
            // patchPackageCount: 0,
            // wholePackageCount: 0,
            versionlists: item.versions.map(version => {
              return {
                id: version.id,
                name: version.name,
                configVersionName: version.configVersionName,
                softwareCode: version.softwareCode,
                description: version.description,
                functionAddition: version.functionAddition,
                functionOptimization: version.functionOptimization,
                acknowledgements: version.acknowledgements
              }
            })
          };
        }).map(ecuVersion => {
          const selectedVersion = this.defaultVersions ? this.defaultVersions[ecuVersion.ecuId] : null
          if (!selectedVersion) {
            ecuVersion.versionType = this.versionType;
            // if (ecuVersion.versionlists.length > 0) {
            //   this.handleSelectVersion(ecuVersion.versionlists[0].id, ecuVersion, ecuVersion.versionlists[0])
            // }
          } else {
            //ecu当前选择版本的类型
            ecuVersion.versionType = selectedVersion.versionType;
            ecuVersion.versionName = selectedVersion.versionName;
            this.handleSelectVersion(selectedVersion.versionId, ecuVersion, selectedVersion)
            defaultEcuLists.push({
              ecuModuleId: ecuVersion.ecuModuleId,
              ecuId: ecuVersion.ecuId,
              versionId: ecuVersion.versionId,
              versionName: selectedVersion.versionName,
              groupNo: ecuVersion.groupNo,
              groupRollback: ecuVersion.groupRollback,
              groupUpgradeNo: ecuVersion.groupUpgradeNo,
              softwareCode: ecuVersion.softwareCode
            })
          }
          this.ecuVersionsList.forEach((item) => {
            if (item.ecuModuleId === ecuVersion.ecuModuleId) {
              ecuVersion.configVersionName = item.version.configVersionName
            }
          })
          return ecuVersion;
          // return {
          //   ...ecuVersion
          // }
        })
        this.defaultEcuConfigLists = defaultEcuLists
        if (this.defaultVersions) {
          this.selectedRowKeys = Object.keys(this.defaultVersions)
        }
      })).finally(() => {
        this.loadingTbData = false
      })
    },
    resetData () {
      this.ecuVersionLists = []
      this.selectedRowKeys = []
      this.releaseNotes = null
    },
    // 选择版本、设置ECU版本信息到ECU行上
    handleSelectVersion (id, ecu, curVersionInfo = {}, handlerSelect = false) {
      // 如果是手动切换则需要清空筛选框
      if (handlerSelect) {
        this.selectedRowKeys = this.selectedRowKeys.filter(item => item !== ecu.ecuId)
        console.log(this.selectedRowKeys)
      }
      ecu.versionId = id
      ecu.configVersionName = curVersionInfo.configVersionName
      // ecu.softwareCode = curVersionInfo.softwareCode
      ecu.releaseNotes = {
        description: curVersionInfo.description,
        functionAddition: curVersionInfo.functionAddition,
        functionOptimization: curVersionInfo.functionOptimization,
        acknowledgements: curVersionInfo.acknowledgements
      }
      this.releaseNotes = ecu.releaseNotes
      if (!id) {
        ecu.patchPackageCount = undefined;
        ecu.wholePackageCount = 0;
        //触发表格更新，更新勾选框状态
        this.ecuVersionLists = [...this.ecuVersionLists]
        return;
      }
      // 每次获取最实时的包数量和状态
      this.$api.getPackageCounVersionId(id).then((res) => {
        // this.ecuVersionLists.forEach((element) => {
        //   if (element.versionId === id) {
        ecu.patchPackageCount = res.data.patchPackageCount;
        ecu.wholePackageCount = res.data.wholePackageCount;
            // this.$set(ecu, 'patchPackageCount', res.data.patchPackageCount)
            // this.$set(ecu, 'wholePackageCount', res.data.wholePackageCount)
        //   }
        // })
        //触发表格更新，更新勾选框状态
        this.ecuVersionLists = [...this.ecuVersionLists]
      });
    },
    // 选择回滚
    handleSelectRollback (data, record) {
      if (data === 1) {
        record.groupRollback = true;
      }else if (data === 0) {
        record.groupRollback = false;
      } else {
        record.groupRollback = undefined;
      }
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 获取选择的零件版本配置数据
    getConfigData () {
      // 零件版本配置是否未修改
      const data = this.selectedRowKeys.map((id) => {
        const selectedRow = this.ecuVersionLists.find((list) => list.ecuId === id)
        if (!selectedRow) {
          return null
        }
        return {
          ecuModuleId: selectedRow.ecuModuleId,
          ecuId: selectedRow.ecuId,
          versionId: selectedRow.versionId,
          groupNo: selectedRow.groupNo,
          groupRollback: selectedRow.groupRollback,
          groupUpgradeNo: selectedRow.groupUpgradeNo,
          softwareCode: selectedRow.softwareCode,
          patchPackageCount: selectedRow.patchPackageCount,
          wholePackageCount: selectedRow.wholePackageCount
        }
      })
      return data
    },
    // 检测编辑时是否有更改列表信息
    checkConfigIsDiff (newLists) {
      //长度不一样、长度相同有不完全相等项
      return (
        this.defaultEcuConfigLists.length !== newLists.length ||
        this.defaultEcuConfigLists.some((item) => {
          return (
            newLists.findIndex((list) => {
              return (
                list.ecuId === item.ecuId &&
                list.versionId === item.versionId &&
                list.ecuModuleId === item.ecuModuleId &&
                list.groupNo === item.groupNo &&
                list.groupRollback === item.groupRollback &&
                list.groupUpgradeNo === item.groupUpgradeNo &&
                list.softwareCode === item.softwareCode
              )
            }) === -1
          )
        })
      )
    },
    // 查看版本描述
    showVersionDesc (record) {
      console.log(record, record.versionName, record.versionlists, 'versionlists')
      const versionlist = record.versionlists.filter((item) => {
        return item.name === record.versionName
      })
      if (record.releaseNotes.description === undefined) {
        this.releaseNotes = {
          description: versionlist[0].description,
          functionAddition: versionlist[0].functionAddition,
          functionOptimization: versionlist[0].functionOptimization,
          acknowledgements: versionlist[0].acknowledgements
        }
      }
      this.$refs.releaseNoteRef.toggleVisible(true)
    }
  }
}
</script>
